package com.example.hadoop.mapreduce.orderjoin;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: Brian
 * @Date: 2020/04/26/0:09
 * @Description:
 */
public class OrderJoinDriver {

    static class OrderJoinMapper extends Mapper<LongWritable, Text, Text, OrderInfoBean> {

        Text v = new Text();
        OrderInfoBean bean = new OrderInfoBean();

        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            //根据文件名判断是order的信息还是产品的信息
            FileSplit fileSplit = (FileSplit) context.getInputSplit();
            Path filePath = fileSplit.getPath();
            String line = value.toString();
            String[] splits = line.split("\t");
            String productId = "";
            //OrderInfo
            if (filePath.getName().startsWith("t_order")) {
                productId = splits[2];
                bean.setOrderInfo(splits[0], splits[1], productId, Double.parseDouble(splits[3]));
            } else {
                // productInfo
                productId = splits[0];
                bean.setProductInfo(productId, splits[1], splits[2], Double.parseDouble(splits[3]));
            }
            v.set(productId);
            context.write(v, bean);
        }
    }

    static class OrderJoinReducer extends Reducer<Text, OrderInfoBean, OrderInfoBean, NullWritable> {

        OrderInfoBean productInfo = new OrderInfoBean();

        /**
         * <productId1, ProductInfo1><productId1,OrderInfo1><productId1,OrderInfo2><productId2,ProductInfo2>
         * <productId3, ProductInfo3><productId3,OrderInfo4><productId3,OrderInfo5><productId4,ProductInfo4>
         *
         * @param key
         * @param values
         * @param context
         * @throws IOException
         * @throws InterruptedException
         */
        @Override
        protected void reduce(Text key, Iterable<OrderInfoBean> values, Context context) throws IOException, InterruptedException {
            List<OrderInfoBean> orderInfoBeans = new ArrayList<>();
            try {
                for (OrderInfoBean bean : values) {
                    if (bean.isOrderInfo()) {
                        OrderInfoBean order = new OrderInfoBean();
                        BeanUtils.copyProperties(order, bean);
                        orderInfoBeans.add(order);
                        continue;
                    }
                    BeanUtils.copyProperties(productInfo, bean);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            //拿到了一个product info 和所有的相同product下的order info
            for (OrderInfoBean bean : orderInfoBeans) {
                bean.setProductName(productInfo.getProductName());
                bean.setCategoryId(productInfo.getCategoryId());
                bean.setPrice(productInfo.getPrice());
                context.write(bean, NullWritable.get());
            }
        }
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        if (args == null || args.length < 2) {
            args[0] = "/wordcount/flowinput";
            args[1] = "/wordcount/flowoutput";
        }

        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf);

        //设置jar包路径
        job.setJarByClass(OrderJoinDriver.class);

        //设置Map Reduce类
        job.setMapperClass(OrderJoinMapper.class);
        job.setReducerClass(OrderJoinReducer.class);

        //设置Map输出
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(OrderInfoBean.class);
        //设置最终输出
        job.setOutputKeyClass(OrderInfoBean.class);
        job.setOutputValueClass(NullWritable.class);

        //设置输入输出路径
        FileInputFormat.setInputPaths(job, new Path(args[0]));
        Path outputPath = new Path(args[1]);
        FileSystem fileSystem = FileSystem.get(conf);
        if (fileSystem.exists(outputPath)) {
            fileSystem.delete(outputPath, true);
        }
        FileOutputFormat.setOutputPath(job, outputPath);

        boolean successful = job.waitForCompletion(true);
        System.out.println("Successfully? --> " + successful);
        System.exit(successful ? 0 : 1);
    }
}
